<script setup>
import { ref } from 'vue'
import 'uno.css'
import { sendMessage } from 'webext-bridge/content-script'
import { enablePlugin } from '~/logic'

const selectedText = ref('')
const bubblePosition = ref({ x: 0, y: 0 })
const isLoading = ref(false)
const isTranslated = ref(false)
const showBubble = ref(false)

// 检查是否不包含中文字符
function hasChinese(text) {
  // 匹配中文字符的正则表达式
  const chineseRegex = /[\u4E00-\u9FFF]/
  // 返回 true 如果包含中文字符
  return chineseRegex.test(text)
}

// 检查单词数量是否超过50
function isWordCountValid(text) {
  const wordCount = text.trim().split(/\s+/).length
  return wordCount <= 200
}

// 计算气泡位置，确保不超出视口
function calculateBubblePosition(rect) {
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight
  const bubbleWidth = 300 // 增加预估气泡宽度
  const bubbleHeight = 100 // 增加预估气泡高度，考虑多行文本

  let x = rect.right + 8
  let y = rect.top

  // 处理右边界
  if (x + bubbleWidth > viewportWidth) {
    x = rect.left - bubbleWidth - 8
  }

  // 处理上下边界
  if (y < bubbleHeight / 2) {
    y = bubbleHeight / 2
  }
  else if (y > viewportHeight - bubbleHeight / 2) {
    y = viewportHeight - bubbleHeight / 2
  }

  // 转换为视口相对位置
  return {
    x,
    y,
  }
}

onmouseup = async () => {
  const selection = window.getSelection()
  const text = selection.toString().trim()

  if (text && !hasChinese(text) && isWordCountValid(text) && enablePlugin.value) {
    const range = selection.getRangeAt(0)
    const rect = range.getBoundingClientRect()
    const position = calculateBubblePosition(rect)

    selectedText.value = text
    isLoading.value = true
    isTranslated.value = false
    bubblePosition.value = position

    showBubble.value = true

    try {
      const translatedTxt = await sendMessage('translate', text)
      selectedText.value = translatedTxt
      isTranslated.value = true
    }
    catch (error) {
      console.error('Translation failed:', error)
    }
    finally {
      isLoading.value = false
    }
  }
  else {
    showBubble.value = false
    setTimeout(() => {
      selectedText.value = ''
      isLoading.value = false
      isTranslated.value = false
    }, 300)
  }
}
</script>

<template>
  <div
    v-if="selectedText"
    class="selection-bubble fixed px-4 py-2 rounded-lg shadow-lg z-50 text-sm"
    :class="{
      'opacity-0 translate-x-1': !showBubble,
      'opacity-100 translate-x-0': showBubble,
      'bg-white': isLoading,
      'bg-gradient-to-r from-blue-500 to-blue-600 text-white': isTranslated,
    }"
    :style="{
      position: 'fixed',
      left: `${bubblePosition.x}px`,
      top: `${bubblePosition.y}px`,
    }"
  >
    <div class="bubble-content">
      {{ selectedText }}
    </div>
  </div>
</template>

<style scoped>
.selection-bubble {
  position: fixed;
  transform: translateY(-50%);
  backdrop-filter: blur(8px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  max-width: 300px;
}

.bubble-content {
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  line-height: 1.5;
  max-height: 200px;
  overflow-y: auto;
}

.selection-bubble.opacity-0 {
  opacity: 0;
  transform: translateY(-50%) translateX(10px);
}

.selection-bubble.opacity-100 {
  opacity: 1;
  transform: translateY(-50%) translateX(0);
}

.selection-bubble {
  transition: background-color 0.3s ease,
              background-image 0.3s ease,
              transform 0.3s ease,
              opacity 0.3s ease,
              color 0.3s ease;
}

.selection-bubble:hover {
  transform: translateY(-50%) translateX(2px);
}

/* 添加滚动条样式 */
.bubble-content::-webkit-scrollbar {
  width: 4px;
}

.bubble-content::-webkit-scrollbar-track {
  background: transparent;
}

.bubble-content::-webkit-scrollbar-thumb {
  background: rgba(155, 155, 155, 0.5);
  border-radius: 2px;
}

.bubble-content::-webkit-scrollbar-thumb:hover {
  background: rgba(155, 155, 155, 0.7);
}
</style>
